package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.Article;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 阅读量加 1
 */
@WebServlet("/addrcount")
public class AddReadCountServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg="未知参数";
        int data=0;
        //1.从前端获取用户的参数
        String aidStr=req.getParameter("aid");
        if(!StrUtil.isBlank(aidStr)){
            int aid=Integer.valueOf(aidStr);
            if(aid>0){
                //2.将访问量+1，得到执行的结果
                Connection connection= DBUtils.getConnection();
                String sql="update article set readcount=readcount+1 where aid=?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,aid);
                data = statement.executeUpdate();

                DBUtils.close(null,statement,connection);

            }else{
                msg="非法错误";
            }
        }else{
            msg="参数错误";
        }

        //3.将数据返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
